package edu.bupt.changelog.history.aop;

import edu.bupt.changelog.history.anno.HistoryPut;
import edu.bupt.changelog.history.HistoryRegistion;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;


// https://blog.csdn.net/u012098021/article/details/116802329
@Aspect
@Component
public class HistoryAop {
    @Resource
    private ChangeSaver changeSaver;


    @Pointcut("@annotation(edu.bupt.changelog.history.anno.HistoryPut)")
    public void pointCut1() {}

    @Around("pointCut1()")
    public Object around(ProceedingJoinPoint joinPoint){
        System.out.println("=====================进入aop");

        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        HistoryPut annotation = method.getAnnotation(HistoryPut.class);
        final Class enityClazz = annotation.value().getEntityClass();

        Object[] args = joinPoint.getArgs();
        // todo assert args.length > 0
        final Object userParam = args[0];
        // spring在找到有get的实例后，会balabala;
        Object oldEntity = HistoryRegistion.get(userParam, enityClazz);

        Object obj = null;
        try {
            obj = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        Object newEntity = HistoryRegistion.get(userParam, enityClazz);

        // todo 应该还有entityType;
        changeSaver.save(oldEntity,newEntity);

        return obj;
    }

}
